/*
    在线翻译字典服务器: 利用muduo库快速搭建一个翻译服务器
*/
#include <iostream>
#include <string>
#include "muduo/net/EventLoop.h"
#include "muduo/net/TcpServer.h"
#include "muduo/net/TcpConnection.h"

// 翻译服务器类
class TranslateServer
{ 
public:
    TranslateServer(int port, const std::string& ip = "0.0.0.0") :
        _server(&_base_loop, muduo::net::InetAddress(ip, port), "TranslateServer", muduo::net::TcpServer::kReusePort)
    {
        _server.setConnectionCallback(std::bind(&TranslateServer::onConnection, this, std::placeholders::_1));
        _server.setMessageCallback(std::bind(&TranslateServer::onMessage, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
    }

    void start()
    {
        std::cout << "server is start..." << std::endl;
        _server.start();
        _base_loop.loop();
    }

private:
    // 当连接建立和断开时回调函数
    void onConnection(const muduo::net::TcpConnectionPtr& conn)
    {
        if(conn->connected())
            std::cout << "connection is established" << std::endl;
        else
            std::cout << "connection is closed" << std::endl;
    }

    // 当接收到消息时的回调函数
    void onMessage(const muduo::net::TcpConnectionPtr& conn, muduo::net::Buffer* buf, muduo::Timestamp)
    {
        // 1. 获取用户发送的消息
        std::string msg = buf->retrieveAllAsString();

        // 2. 业务处理
        std::string res = translate(msg);

        // 3. 发送响应
        conn->send(res);
    }

    // 翻译处理函数
    std::string translate(std::string msg)
    {
        std::map<std::string, std::string> dict = {{"hello", "你好"}, {"world", "世界"}, {"muduo", "muduo库"}};
        return dict[msg];
    }

private:
    muduo::net::EventLoop _base_loop;
    muduo::net::TcpServer _server;
};


int main()
{
    TranslateServer server(8080);
    server.start();
    return 0;
}